package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.constant.BusinessStatusConstants;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.CurrentUserContextHolders;
import com.qk.domain.business.BusinessDO;
import com.qk.dto.business.BusinessDTO;
import com.qk.dto.business.PoolDTO;
import com.qk.dto.business.UpdateBusinessInfoDTO;
import com.qk.entity.Business;
import com.qk.entity.BusinessTrackRecord;

import com.qk.entity.Customer;
import com.qk.entity.User;
import com.qk.management.mapper.*;
import com.qk.management.service.BusinessService;
import com.qk.vo.business.BusinessListVO;
import com.qk.vo.business.BusinessQueryVO;
import com.qk.vo.business.PoolVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author: Enid
 * @date: 2025/10/16 11:52
 * @description:
 */
@Slf4j
@Service
@SuppressWarnings("all")
public class BusinessServiceImpl extends ServiceImpl<BusinessMapper, Business> implements BusinessService {
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private BusinessTrackRecordMapper businessTrackRecordMapper;
    @Autowired
    private CustomerMapper customerMapper;

    @Override
    public void toCustomer(Integer id) {
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.TO_BUSINESS);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);

        Customer customer = BeanUtil.copyProperties(business, Customer.class);
        customer.setId(null);
        customer.setBusinessId(business.getId());
        customer.setCreateTime(LocalDateTime.now());
        customer.setUpdateTime(LocalDateTime.now());
        customerMapper.insert(customer);

    }

    @Override
    public void back(Integer id) {
        //修改商机的状态，将该商机的状态修改为 4 。
        Business business = this.baseMapper.selectById(id);
        business.setStatus(BusinessStatusConstants.FALSE_CLUE);
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.updateById(business);
    }

    @Override
    public PageResult<PoolVO> poolList(PoolDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<PoolVO> result = businessMapper.poolList(dto);
        Page<PoolVO> page = (Page<PoolVO>) result;
        return PageResult.<PoolVO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }

    @Override
    public void updateClueInfoById(UpdateBusinessInfoDTO dto) {
        Business business = this.baseMapper.selectById(dto.getId());
        business.setUpdateTime(LocalDateTime.now());
        if (Objects.equals(dto.getStatus(), BusinessStatusConstants.WAIT_ALLOCATION)){
            business.setStatus(BusinessStatusConstants.WAIT_FOLLOW_UP);
        }
        this.baseMapper.updateById(business);

        BusinessTrackRecord businessTrackRecord = BeanUtil.copyProperties(dto, BusinessTrackRecord.class);
        businessTrackRecord.setId(null);
        businessTrackRecord.setBusinessId(dto.getId());
        businessTrackRecord.setUserId(CurrentUserContextHolders.get());
        businessTrackRecord.setCreateTime(LocalDateTime.now());
        businessTrackRecordMapper.insert(businessTrackRecord);
    }

    @Override
    public BusinessQueryVO getBusinessInfoById(Integer id) {

        Business business = this.baseMapper.selectById(id);
        BusinessQueryVO businessQueryVO= BeanUtil.copyProperties(business, BusinessQueryVO.class);

        User user = userMapper.selectById(business.getUserId());
        List<BusinessTrackRecord>  businessTrackRecordList = businessTrackRecordMapper.selectList(Wrappers.lambdaQuery(BusinessTrackRecord.class)
                .eq(BusinessTrackRecord::getBusinessId, id)
        );

        List<BusinessQueryVO.BusinessTrackRecordVO> list =businessTrackRecordList.stream().map(item -> {
            BusinessQueryVO.BusinessTrackRecordVO vo = BeanUtil.copyProperties(item, BusinessQueryVO.BusinessTrackRecordVO.class);
            vo.setAssignName(user.getName());
            return vo;
        }).toList();
        businessQueryVO.setTrackRecords(list);
        log.info("查询结果：{}",businessQueryVO);
        return businessQueryVO;
    }

    @Override
    public void addBusiness(BusinessDO businessDO) {
        if (ObjectUtil.isEmpty(businessDO.getName()) || ObjectUtil.isEmpty(businessDO.getPhone())) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        Business business = BeanUtil.copyProperties(businessDO, Business.class);
        business.setStatus(BusinessStatusConstants.WAIT_ALLOCATION);
        business.setUserId(null);
        business.setClueId(null);
        business.setCreateTime(LocalDateTime.now());
        business.setUpdateTime(LocalDateTime.now());
        this.baseMapper.insert(business);

    }

    @Override
    public PageResult<BusinessListVO> pageList(BusinessDTO dto) {
        PageHelper.startPage(dto.getPage(), dto.getPageSize());
        List<BusinessListVO> result = businessMapper.pageList(dto);
        Page<BusinessListVO> page = (Page<BusinessListVO>) result;
        return PageResult.<BusinessListVO>builder()
                .total(Long.valueOf(page.getTotal()).intValue())
                .rows(page.getResult())
                .build();
    }
}
